package org.example.test.test02.t01;

import java.sql.*;

/**
 *
 */
public class DBUtils {
    //一般情况下，我们将加载驱动的步骤，放到static静态块中
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    private static String url = "jdbc:mysql://localhost:3306/example";
    private static String user = "root";
    private static String password = "root";
    // 取得连接
    public static Connection getConn() throws SQLException {
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    // 关闭资源
    /*
        对于资源的关闭，分为两种情况
        添加 修改 删除 需要关闭的资源有 Statement  Connection
        查询 需要关闭的资源有 ResultSet Statement  Connection
     */
    public static void close(Connection conn, Statement stat, ResultSet rs){
        if (null != rs){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != stat){
            try {
                stat.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 方法重载
    public static void close(Connection conn, Statement stat){
        if (null != stat){
            try {
                stat.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
